package com.quanyan.alipay.protocal;


import com.quanyan.alipay.config.AlipayConfig;
import com.quanyan.alipay.sign.MD5;
import com.quanyan.alipay.util.AlipayCore;
import com.quanyan.alipay.util.AlipayNotify;
import com.quanyan.alipay.util.AlipaySubmit;
import com.quanyan.alipay.util.UtilDate;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by zijun.song on 2015/9/22.
 */
public class AliPayRefundData {

    private String service;

    private String partner;

    private String _input_charset;

    private String notify_url;

    private String seller_email; //卖家支付宝email

    private String refund_date; //必填，格式：年[4位]-月[2位]-日[2位] 小时[2位 24小时制]:分[2位]:秒[2位]，如：2007-10-01 13:13:13

    private String batch_no; //必填，格式：当天日期[8位]+序列号[3至24位]，如：201008010000001

    private String batch_num; ////必填，参数detail_data的值中，“#”字符出现的数量加1，最大支持1000笔（即“#”字符出现的数量999个）

    private String detail_data; ////必填，具体格式请参见接口技术文档

    private AliPayRefundData(String batch_no, String detail_data, AlipayConfig alipayConfig) {
        this.service = "refund_fastpay_by_platform_pwd";
        this.partner = alipayConfig.getPartner();
        this._input_charset = alipayConfig.getInput_charset();
        this.notify_url = alipayConfig.getRefund_notify_url();
        this.seller_email = alipayConfig.getSeller();
        this.refund_date = UtilDate.getDateFormatter();
        this.batch_num = "1";
        this.batch_no = batch_no;
        this.detail_data = detail_data;
    }


    private AliPayRefundData(String batch_no, String detail_data, int batch_num, AlipayConfig alipayConfig) {
        this(batch_no, detail_data, alipayConfig);
        this.batch_num = batch_num + "";
    }


    public String getService() {
        return service;
    }

    public void setService(String service) {
        this.service = service;
    }

    public String getPartner() {
        return partner;
    }

    public void setPartner(String partner) {
        this.partner = partner;
    }

    public String get_input_charset() {
        return _input_charset;
    }

    public void set_input_charset(String _input_charset) {
        this._input_charset = _input_charset;
    }

    public String getNotify_url() {
        return notify_url;
    }

    public void setNotify_url(String notify_url) {
        this.notify_url = notify_url;
    }

    public String getSeller_email() {
        return seller_email;
    }

    public void setSeller_email(String seller_email) {
        this.seller_email = seller_email;
    }

    public String getRefund_date() {
        return refund_date;
    }

    public void setRefund_date(String refund_date) {
        this.refund_date = refund_date;
    }

    public String getBatch_no() {
        return batch_no;
    }

    public void setBatch_no(String batch_no) {
        this.batch_no = batch_no;
    }

    public String getBatch_num() {
        return batch_num;
    }

    public void setBatch_num(String batch_num) {
        this.batch_num = batch_num;
    }

    public String getDetail_data() {
        return detail_data;
    }

    public void setDetail_data(String detail_data) {
        this.detail_data = detail_data;
    }

    private static AliPayRefundData getInstance(String tsn, BigDecimal amount, String reason, String batch_no, AlipayConfig alipayConfig) {
        return new AliPayRefundData(batch_no, tsn + "^" + amount.toString() + "^" + reason, alipayConfig);
    }

    public static String buildRequest(String batch_no, int batch_num, String detail_data, AlipayConfig alipayConfig) {
        AliPayRefundData aliPayRefundData = new AliPayRefundData(batch_no, detail_data, batch_num, alipayConfig);
        Map<String, String> map = objectToMapString(aliPayRefundData);
        return AlipaySubmit.buildRequest(map, "GET", "确认", alipayConfig);
    }

    /**
     * @param tsn           //淘宝交易订单号
     * @param amount
     * @param reason
     * @param refundOrderNo
     * @return
     */
    public static String buildRequest(String tsn, BigDecimal amount, String reason, String refundOrderNo, AlipayConfig alipayConfig) {
        Map<String, String> map = objectToMapString(getInstance(tsn, amount, reason, refundOrderNo, alipayConfig));
        String sHtmlText = AlipaySubmit.buildRequest(map, "GET", "确认", alipayConfig);
        return sHtmlText;
    }

    public static boolean verify(Map<String, String> map, AlipayConfig alipayConfig) {
        String responseTxt = "true";
        if (map.get("notify_id") != null) {
            String notify_id = map.get("notify_id");
            responseTxt = AlipayNotify.verifyResponse(notify_id, alipayConfig);


        }
        String sign = map.get("sign");
        String content = AlipayCore.createLinkString(AlipayCore.paraFilterContainSignType(map));
        return MD5.verify(content, sign, alipayConfig.getKey(), alipayConfig.getInput_charset()) && responseTxt.equals("true");
    }


    /**
     * 将对象转换为map
     *
     * @param object
     * @return
     */
    public static Map<String, String> objectToMapString(Object object) {
        if (object == null) {
            return null;
        }
        Map<String, String> map = new HashMap<String, String>();
        Field[] fields = object.getClass().getDeclaredFields();
        for (Field field : fields) {
            Object obj;
            try {
                field.setAccessible(true);
                obj = field.get(object);
                if (obj != null) {
                    if (obj instanceof Date) {
                        map.put(field.getName(), ((Date) obj).getTime() + "");
                    } else {
                        map.put(field.getName(), obj.toString());

                    }
                }
                field.setAccessible(false);
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return map;
    }
}
